<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editor"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="min-height: 300px; text-align: left;"
      v-model="html"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="onCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose, getCurrentInstance, ComponentInternalInstance, onUnmounted } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { ElMessage, ElMessageBox } from 'element-plus';

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;

// 实例
const editor = ref(null) as any;
const html = ref('');
const toolbarConfig = reactive({
  excludeKeys: ['uploadImage', 'uploadVideo', 'insertVideo'],
});
const editorConfig = reactive({
  placeholder:
    '请输入内容...<br/>温馨提示：上传视频功能还未开发，暂时无法上传视频',
  MENU_CONF: {},
});
const mode = ref('default');  // or 'simple'

// 创建富文本编辑器实例对象
function onCreated(Editor: any) {
  editor.value = Object.seal(Editor); // 一定要用 Object.seal() ，否则会报错
};

function getValue() {
  return html.value;
};
function clear() {
  ElMessageBox.confirm('此操作将会清空文本框里的所有内容, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      proxy.$request.account.logout().then(() => {
        html.value = '';
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
      });
    });
};

defineExpose({
  getValue,
  clear
})

onUnmounted(() => {
  const Editor = editor.value;
  if (Editor === null) return;
  Editor.destroy(); // 组件销毁时，及时销毁编辑器
});
</script>
